package com.itjeffrey.autocode.runner;

import com.itjeffrey.autocode.constant.SysConstant;
import com.itjeffrey.autocode.util.FileUtil;
import com.itjeffrey.autocode.util.TemplateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *  实现CommandLineRunner接口；容器启动之后，加载实现类的逻辑资源，已达到完成资源初始化的任务
 *  多个CommandLineRunner实现类，添加@Order注解，设置加载顺序，order值越小加载越优先
 * @From: Jeffrey
 * @Date: 2021/6/24
 */
@Slf4j
@Component
@Order(value = 1)
public class TemplateInitRunner implements CommandLineRunner {

    /**
     * template map
     * key: templateName, value: templateString
     */
    private Map<String, String> templateMap = new HashMap<>();

    /**
     * init all the system`s templates after starting this project.
     * @param args
     * @throws Exception
     */
    @Override
    public void run(String... args) throws Exception {
        //对读取模板文件进行计时
        StopWatch sw = new StopWatch("file_read");
        sw.start();
        List<String> fileNames = FileUtil.getFileNames(System.getProperty(SysConstant.USER_DIR) + SysConstant
                .MODEL_ABSTRACT_PATH);
        for (String fileName : fileNames) {
            String modelStr = TemplateUtil.fileToStr(fileName);
            templateMap.put(fileName, modelStr);
        }
        sw.stop();
        long totalTimeMillis = sw.getTotalTimeMillis();
        log.info("Init template count:{}, cost:{}ms", templateMap.size(), totalTimeMillis);
    }

    public Map<String, String> getTemplateMap(){
        return this.templateMap;
    }

}
